package com.xjzd.ftp;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FTPUtil {

    public static FTPClient connectFtpServer(String addr, int port, String username, String password, String controlEncoding) {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.setControlEncoding(controlEncoding);
            ftpClient.connect(addr, port);
            if (StringUtils.isBlank(username)) {
                ftpClient.login("Anonymous", "");
            } else {
                ftpClient.login(username, password);
            }

            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.abort();
                ftpClient.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(">>>>>FTP服务器连接登录失败，请检查连接参数是否正确，或者网络是否通畅*********");
        }
        return ftpClient;
    }

    public static FTPClient closeFTPConnect(FTPClient ftpClient) {
        try {
            if (ftpClient != null && ftpClient.isConnected()) {
                ftpClient.abort();
                ftpClient.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ftpClient;
    }

    public static void uploadFiles(FTPClient ftpClient, File uploadFile, String remote) {
        if (!ftpClient.isConnected() || !ftpClient.isAvailable()) {
            System.out.println(">>>>>FTP服务器连接已经关闭或者连接无效*****放弃文件上传****");
            return;
        }
        if (uploadFile == null || !uploadFile.exists()) {
            System.out.println(">>>>>待上传文件为空或者文件不存在*****放弃文件上传****");
            return;
        }
        try {
            /**如果被上传的是文件时*/
            FileInputStream input = new FileInputStream(uploadFile);
            /** storeFile:将本地文件上传到服务器
             * 1）如果服务器已经存在此文件，则不会重新覆盖,即不会再重新上传
             * 2）如果当前连接FTP服务器的用户没有写入的权限，则不会上传成功，但是也不会报错抛异常
             * */
            ftpClient.storeFile(remote, input);
            input.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        FTPClient ftpClient = connectFtpServer("172.17.100.106", 2121, "miao", "xjzd!@#$", "utf-8");
        if (ftpClient.changeWorkingDirectory("/test")) {
            System.out.println("changeWorkingDirectory successfully");
        } else {
            System.out.println("changeWorkingDirectory failed");
        }
        uploadFiles(ftpClient, new File("E:\\金职位\\1-5.表单标签.mp4"), "1-5.表单标签.mp4");
        closeFTPConnect(ftpClient);
    }
}